package cn.cao.domain.order.service;

import cn.cao.domain.order.adapter.port.IProductPort;
import cn.cao.domain.order.adapter.repository.IOrderRepository;
import cn.cao.domain.order.model.aggregate.CreateOrderAggregate;
import cn.cao.domain.order.model.entity.OrderEntity;
import cn.cao.domain.order.model.entity.PayOrderEntity;
import cn.cao.domain.order.model.entity.ProductEntity;
import cn.cao.domain.order.model.entity.ShopCartEntity;
import cn.cao.domain.order.model.valobj.OrderStatusVO;
import com.alipay.api.AlipayApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @Author caoyi
 * @description:
 * @Date 2025/7/11 17:52
 */
@Slf4j
public abstract class AbstractOrderService implements IOrderService {

    protected final IOrderRepository repository;
    protected final IProductPort port;

    public AbstractOrderService(IOrderRepository repository, IProductPort port) {
        this.repository = repository;
        this.port = port;
    }

    @Override
    public PayOrderEntity createOrder(ShopCartEntity shopCartEntity) throws Exception {
        // 1. 查询当前用户是否存在未支付订单或掉单订单
        OrderEntity unpaidOrder = repository.queryUnPayOrder(shopCartEntity);

        if (null != unpaidOrder && OrderStatusVO.PAY_WAIT.equals(unpaidOrder.getOrderStatusVO())) {
            log.info("创建订单-存在，已存在未支付订单。userId:{} productId:{} orderId:{}", shopCartEntity.getUserId(), shopCartEntity.getProductId(), unpaidOrder.getOrderId());
            return PayOrderEntity.builder()
                    .orderId(unpaidOrder.getOrderId())
                    .payUrl(unpaidOrder.getPayUrl())
                    .build();
        } else if (null != unpaidOrder && OrderStatusVO.CREATE.equals(unpaidOrder.getOrderStatusVO())){
            //已经有流水单，创建支付单
            log.info("创建订单-存在，存在未创建支付单订单，创建支付单开始 userId:{} productId:{} orderId:{}", shopCartEntity.getUserId(), shopCartEntity.getProductId(), unpaidOrder.getOrderId());
            //由子类实现创建支付单
            PayOrderEntity payOrderEntity = doPrepayOrder(shopCartEntity.getUserId(), shopCartEntity.getProductId(), unpaidOrder.getProductName(), unpaidOrder.getOrderId(), unpaidOrder.getTotalAmount());
            return PayOrderEntity.builder()
                    .orderId(payOrderEntity.getOrderId())
                    .payUrl(payOrderEntity.getPayUrl())
                    .build();

        }

        // 2. 查询商品 & 创建订单
        //因为实际业务中商品表往往不在这个业务中，要通过RPC的方式，所以不能用仓储获得，应该用port从而处理
        ProductEntity productEntity = port.queryProductByProductId(shopCartEntity.getProductId());

        //创建order流水单（通过聚合对象去做）
        OrderEntity orderEntity = CreateOrderAggregate.buildOrderEntity(productEntity.getProductId(), productEntity.getProductName());

        //接下来的操作只是为了抽象类的扩展
        CreateOrderAggregate orderAggregate = CreateOrderAggregate.builder()
                .userId(shopCartEntity.getUserId())
                .productEntity(productEntity)
                .orderEntity(orderEntity)
                .build();

        //子类实现保存流水单
        this.doSaveOrder(orderAggregate);

        //子类实现支付单
        PayOrderEntity payOrderEntity = doPrepayOrder(shopCartEntity.getUserId(), shopCartEntity.getProductId(), orderEntity.getProductName(), orderEntity.getOrderId(), productEntity.getPrice());
        log.info("创建订单-完成，生成支付单。userId: {} orderId: {} payUrl: {}", shopCartEntity.getUserId(), orderEntity.getOrderId(), payOrderEntity.getPayUrl());

        return PayOrderEntity.builder()
                .orderId(orderEntity.getOrderId())
                .payUrl(payOrderEntity.getPayUrl())
                .build();
    }

    protected abstract PayOrderEntity doPrepayOrder(String userId, String productId, String productName, String orderId, BigDecimal totalAmount) throws AlipayApiException;

    protected abstract void doSaveOrder(CreateOrderAggregate orderAggregate);
}
